var express = require('express');
var router = express.Router();
var path = require('path');
var fs = require('fs');

const musicMap = new Map([
    ['0001', '高梨康治 (たかなし やすはる) _ 刃-yaiba- (ヤイバ) - 孤独.mp3'],
    ['0002', '音阙诗听 _ 赵方婧 - 芒种.mp3']
])

const mediaPath = path.join(__dirname, '../../public/media');

router.get('/', (req, res, next) => {
    let result = [];
    for (let [key, value] of musicMap.entries()) {
        result.push({
            id: key,
            name: value
        });
    }

    res.json(result);
});

router.get('/:key', (req, res, next) => {
    const key = req.params.key;
    const filename = musicMap.get(key);

    const musicPath = path.join(mediaPath, filename);
    const stream = fs.createReadStream(musicPath);

    stream.pipe(res);

    stream.on('end', () => {
        res.end();
    });
});

module.exports = router;
